import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import DTO.ImageidDTO;
import DTO.LocaldataDTO;
import java.io.*;
@WebServlet("/upload")
@MultipartConfig(location = "C:\\Users\\G\\Desktop\\exp3\\src\\main\\webapp\\picture")// location改为本地的绝对路径
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ImageidDTO imageidDTO;
        if(request.getSession().getAttribute("imageidDTO")!=null){
            imageidDTO=(ImageidDTO)request.getSession().getAttribute("imageidDTO");
            File Del=new File(imageidDTO.getName());
            if(Del.exists()&&Del.isFile()) { System.gc();Del.delete();}
        }
        else {imageidDTO=new ImageidDTO();}
        LocaldataDTO localdataDTO=(LocaldataDTO)request.getSession().getAttribute("localdataDTO");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取请求项，封装成Part对象
        // request.getPart方法的传参为前端页面from表单的input文件组件的name值
        Part part = request.getPart("file");
        // part.getSubmittedFileName()方法获取上传文件的文件名
        String fileName = part.getSubmittedFileName();
        System.out.println("上传文件的文件名: " + fileName);
        // 根据@MultipartConfig的location配置的目录上传文件，直接传参文件名即可。
        part.write(fileName);
        imageidDTO.setUserid(localdataDTO.getUserid());
        imageidDTO.setName(fileName);
        request.getSession().setAttribute("imageidDTO",imageidDTO);
        response.sendRedirect("HomePage.jsp");

    }
}
